//
//  RHDevRelationController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/8/14.
//

#import "RHDevRelationController.h"
#import "RHMQEndPointNodesController.h"
#import "RHMQAddEndPointController.h"
#import "RHMQEndPointModel.h"
#import "RHMQDevRegionModel.h"
#import "RHMQTTManage.h"
#import "RHMQDevModel.h"
#import "SYChartTool.h"

@interface RHDevRelationController ()<UITableViewDelegate ,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *dataArray;

@end

@implementation RHDevRelationController

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"端点关系"];
    [self.view setBackgroundColor:CFTabViewBgColor];
    //[self creatData];
    [self setupUI];
    [self getDevRelation];
}

- (void)creatData{
    
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"MqEndPoint"];
    [self.dataArray addObjectsFromArray:[NSArray yy_modelArrayWithClass:[RHMQEndPointModel class] json:dict[@"data"]]];
    
//
//    NSArray *type_array = @[@"0001",@"0002",@"0003",@"0004"];
//    NSArray *type_name_array = @[@"EMS",@"Master",@"PACK",@"PCS"];
//    NSArray *model_array = @[@"10001",@"10001",@"10001",@"10001"];
//    NSArray *model_name_array = @[@"EMS1",@"Master1",@"PACK1",@"PCS1"];
//    NSArray *model_sn_array = @[@"E00001",@"M00001",@"P00001",@"PC0001"];
//
//    [type_array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        RHMQEndPointModel *model = [[RHMQEndPointModel alloc] init];
//        model.typeCode = obj;
//        model.typeName = type_name_array[idx];
//        model.modelCode = model_array[idx];
//        model.modelName = model_name_array[idx];
//        model.pointSN = model_sn_array[idx];
//
//        [self.dataArray addObject:model];
//    }];
    
}

- (void)setupUI{
    
    QMUIButton *addBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setFrame:CGRectMake(0, 0,40, 64)];
    [addBtn setBackgroundColor:UIColor.clearColor];
    [addBtn setTitleColor:CFMainColor forState:UIControlStateNormal];
    [addBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [addBtn setTitle:@"新增" forState:UIControlStateNormal];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    kWeakSelf;
    [[addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf addEndPoint];
    }];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
   
    
    [self.tableView addHeaderRefresh:^{
        [weakSelf getDevRelation];
    }];
}

#pragma mark - Network
//上报端点关系
- (void)reportedDevRelation{
    NSArray *dictArr = [self.dataArray yy_modelToJSONObject];
    //取第一个EMU
    NSLog(@"---->类型:%@",NSStringFromClass([dictArr class]));
    [QMUITips showLoadingInView:self.view];
    [RHMQEndPointModel startWithCompletionAPIKey:D_reportedDevRelation argument:@{@"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId,@"password":[RHMQTTManage shareMQTTManage].devModel.secretKey,
        @"data":dictArr} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                [QMUITips showSucceed:@"successful"];
                
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
    }];
}

//获取端点关系
- (void)getDevRelation{
    [self.dataArray removeAllObjects];
    [QMUITips showLoadingInView:self.view];
    [RHMQDevRegionModel startGetWithCompletionAPIKey:D_getDevRelation argument:@{@"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [self.tableView endHeaderRefresh];
            if(resultModel.data){
                
                RHMQDevRegionModel *model = resultModel.data;
                
                [model.data enumerateObjectsUsingBlock:^(RHMQEndPointModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [self.dataArray addObject:obj];
                    [obj.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [self.dataArray addObject:obj];
                        [obj.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            [self.dataArray addObject:obj];
                            [obj.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                                [self.dataArray addObject:obj];
                                [obj.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                                                        
                                }];
                            }];
                        }];
                    }];
                }];
                
                [self.tableView reloadData];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
    }];
}


#pragma mark - Action
//上报
- (void)reportedAction{
    [self reportedDevRelation];
}

//新增
- (void)addEndPoint{
    RHMQAddEndPointController *vc = [[RHMQAddEndPointController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    kWeakSelf;
    vc.callBackBlock = ^(RHMQEndPointModel * _Nonnull model) {
        [weakSelf.dataArray addObject:model];
        [weakSelf.tableView reloadData];
    };
}


#pragma mark - UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 200.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    
    QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setBackgroundColor:CFMainColor];
    [btn.layer setCornerRadius:8];
    [btn setTitle:@"上报" forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
    [footView addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(-kBottomToolBar);
        make.height.mas_equalTo(50);
    }];
    
    kWeakSelf;
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf reportedAction];
    }];
    
    return footView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
    [cell.textLabel setTextColor:kCOLOR_HEX(@"666666")];
    
    RHMQEndPointModel *model = self.dataArray[indexPath.row];
    
    QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    BOOL canAdd = [model.type isEqualToString:@"EMS"]||[model.type isEqualToString:@"Master"];
    [btn setImage:canAdd?[UIImage imageNamed:@"arrow"]:nil forState:UIControlStateNormal];
    [btn setTitleColor:kCOLOR_HEX(@"666666") forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [btn setImagePosition:QMUIButtonImagePositionRight];
    [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btn setFrame:CGRectMake(0, 0, 200, 40)];
    [cell setAccessoryView:btn];
    [btn setEnabled:NO];
    
    [cell.textLabel setText:model.type];
    [btn setTitle:model.sn forState:UIControlStateNormal];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHMQEndPointModel *model = self.dataArray[indexPath.row];
    BOOL canAdd = [model.type isEqualToString:@"EMS"]||[model.type isEqualToString:@"Master"];
    if(canAdd){
        RHMQEndPointNodesController *vc = [[RHMQEndPointNodesController alloc] initWithModel:model];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


@end
